import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

///不随状态栏高度变化的应用栏
class SafeAppBar extends StatefulWidget {
  const SafeAppBar({
    Key key,
    this.leading,
    this.automaticallyImplyLeading = true,
    this.title,
    this.actions = const [],
    this.backgroundColor,
    this.brightness = Brightness.dark,
    this.centerTitle = false,
    this.titleSpacing = 10,
    this.toolbarHeight = kToolbarHeight,
  }) : super(key: key);

  final Widget leading;
  final bool automaticallyImplyLeading;
  final Widget title;
  final List<Widget> actions;
  final Color backgroundColor;
  final Brightness brightness;
  final bool centerTitle;
  final double titleSpacing;
  final double toolbarHeight;

  @override
  _SafeAppBarState createState() => _SafeAppBarState();
}

class _SafeAppBarState extends State<SafeAppBar> {
  double _barHeight;

  @override
  void initState() {
    super.initState();

    _barHeight = MediaQueryData.fromWindow(window).padding.top;
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: widget.brightness == Brightness.dark
          ? SystemUiOverlayStyle.light
          : SystemUiOverlayStyle.dark,
      child: Container(
        padding: EdgeInsets.fromLTRB(
            widget.titleSpacing, _barHeight, widget.titleSpacing, 0),
        width: MediaQueryData.fromWindow(window).size.width,
        height: widget.toolbarHeight + _barHeight,
        color: widget.backgroundColor ?? Theme.of(context).primaryColor,
        child: DefaultTextStyle(
          style: TextStyle(
            color: widget.brightness == Brightness.dark
                ? Colors.white
                : Colors.black,
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
          child: IconTheme.merge(
            data: IconThemeData(
              color: widget.brightness == Brightness.dark
                  ? Colors.white
                  : Colors.black,
            ),
            child: NavigationToolbar(
              leading: widget.leading,
              middle: widget.title,
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: widget.actions,
              ),
              centerMiddle: widget.centerTitle,
              middleSpacing: widget.titleSpacing,
            ),
          ),
        ),
      ),
    );
  }
}
